// Server.cpp : implementation file 
// 

#include "stdafx.h" 
#include "TcpServer.h" 
#include "ClientSocket.h" 

#ifdef _DEBUG 
#define new DEBUG_NEW 
#undef THIS_FILE 
static char THIS_FILE[] = __FILE__; 
#endif 

#define WM_USER_CONNECT (WM_USER + 101)

///////////////////////////////////////////////////////////////////////////// 
// CZXZTCPServer 

TcpServer::TcpServer(CDataHandler* pDataHandler)
: m_pDataHandler(pDataHandler)
{ 
    
} 

TcpServer::~TcpServer() 
{ 
    CloseAllSocket(); 
} 


// Do not edit the following lines, which are needed by ClassWizard. 
#if 0 
BEGIN_MESSAGE_MAP(TcpServer, CAsyncSocket) 
    //{{AFX_MSG_MAP(CZXZTCPServer) 
    //}}AFX_MSG_MAP 
END_MESSAGE_MAP() 
#endif	// 0 

///////////////////////////////////////////////////////////////////////////// 
// CZXZTCPServer member functions 
void TcpServer::OnAccept(int iErrorCode)  
{ 
    // TODO: Add your specialized code here and/or call the base class 
    CAsyncSocket::OnAccept(iErrorCode); 
    
    CClientSocket* pSocket = new CClientSocket(m_pDataHandler);
    if (Accept(*pSocket))
    {
        m_mapClients.push_back(pSocket);
        pSocket->AsyncSelect(FD_READ | FD_CLOSE);
    }
    else
    {
        delete pSocket;
    } 
} 

///////////////////////////////////////////////////////////////////////////// 
void TcpServer::CloseSocket(CClientSocket *pSocket) 
{ 
    ClientSocketList::iterator iter = m_mapClients.begin();
    for(; iter != m_mapClients.end(); iter++) 
    { 
        if (*iter == pSocket)
        {
            (*iter)->Close();
            m_mapClients.remove(pSocket);
            break;
        }
    }
} 


///////////////////////////////////////////////////////////////////////////// 
void TcpServer::CloseAllSocket() 
{ 
    ClientSocketList::iterator iter = m_mapClients.begin();
    for(; iter != m_mapClients.end(); iter++) 
    {
        (*iter)->Close();
        delete *iter;
    }

    m_mapClients.clear();
    Close(); 
} 